#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int len=1e5+10,MAXX=1e6+10;;
ll ans;
int T,n;
int a[len],gs[MAXX];
void res(int s,int e){
    if(s>=e)return ;
    int temp[MAXX];
    memset(temp,0,sizeof(temp));
    vector<int>grap;
    for(int i=s;i<=e;i++){
        temp[a[i]]++;
        if(!temp[a[i]])grap.push_back(a[i]);
    }
    int t=grap.size();
    int maxx;
    for(int i=0;i<t;i++){
        int tmp=grap[t];
        if(temp[tmp]>=2)
        maxx=tmp;
    }
    int idx,falg=1;
    ans+=(temp[maxx]-1)*maxx;
    res(1,e);
    res(s,n);
    return ;
}
int main(){
    freopen("color.in","r",stdin);
    freopen("color.out","w",stdout);
    cin>>T;
    while(T--){
        cin>>n;
        memset(gs,0,sizeof(gs));
        for(int i=1;i<=n;i++){
            cin>>a[i];
            gs[a[i]]++;
        }
        res(1,n);
        cout<<ans<<'\n';
    }
    return 0;
}
